"use strict";
var __assign = (this && this.__assign) || function () {
    __assign = Object.assign || function(t) {
        for (var s, i = 1, n = arguments.length; i < n; i++) {
            s = arguments[i];
            for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
                t[p] = s[p];
        }
        return t;
    };
    return __assign.apply(this, arguments);
};
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
    function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
    return new (P || (P = Promise))(function (resolve, reject) {
        function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
        function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
        function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
        step((generator = generator.apply(thisArg, _arguments || [])).next());
    });
};
var __generator = (this && this.__generator) || function (thisArg, body) {
    var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g = Object.create((typeof Iterator === "function" ? Iterator : Object).prototype);
    return g.next = verb(0), g["throw"] = verb(1), g["return"] = verb(2), typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g;
    function verb(n) { return function (v) { return step([n, v]); }; }
    function step(op) {
        if (f) throw new TypeError("Generator is already executing.");
        while (g && (g = 0, op[0] && (_ = 0)), _) try {
            if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t;
            if (y = 0, t) op = [op[0] & 2, t.value];
            switch (op[0]) {
                case 0: case 1: t = op; break;
                case 4: _.label++; return { value: op[1], done: false };
                case 5: _.label++; y = op[1]; op = [0]; continue;
                case 7: op = _.ops.pop(); _.trys.pop(); continue;
                default:
                    if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; }
                    if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; }
                    if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; }
                    if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; }
                    if (t[2]) _.ops.pop();
                    _.trys.pop(); continue;
            }
            op = body.call(thisArg, _);
        } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; }
        if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true };
    }
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.taskSystem = exports.TaskSystem = void 0;
exports.runWorkflow = runWorkflow;
// 模拟细胞管恢复相关函数
function createCellTubeAnabiosis(taskFlowId, parentTaskId) {
    return __awaiter(this, void 0, void 0, function () {
        return __generator(this, function (_a) {
            console.log('创建细胞管复苏任务', { taskFlowId: taskFlowId, parentTaskId: parentTaskId });
            return [2 /*return*/, { id: 'task-' + Date.now() }];
        });
    });
}
function startCellTubeAnabiosis(batchIndex) {
    return __awaiter(this, void 0, void 0, function () {
        return __generator(this, function (_a) {
            console.log('开始细胞管复苏任务');
            console.log('batchIndex:', batchIndex);
            return [2 /*return*/, { success: true }];
        });
    });
}
function slotCellTubeAnabiosisFailed(error) {
    return __awaiter(this, void 0, void 0, function () {
        return __generator(this, function (_a) {
            console.error('细胞管复苏任务失败', error);
            return [2 /*return*/, { success: false, error: error }];
        });
    });
}
// 细胞数据
var cellData = {
    id: 'cell-001',
    type: 'stem-cell',
    status: 'frozen'
};
var TaskSystem = /** @class */ (function () {
    function TaskSystem() {
        // 任务注册表
        this.taskRegistry = new Map();
    }
    // 注册任务
    TaskSystem.prototype.registerTask = function (taskPath, handlers) {
        this.taskRegistry.set(taskPath, handlers);
    };
    // 执行任务
    TaskSystem.prototype.executeTask = function (taskPath_1) {
        return __awaiter(this, arguments, void 0, function (taskPath, params) {
            var task, result, error_1;
            if (params === void 0) { params = {}; }
            return __generator(this, function (_a) {
                switch (_a.label) {
                    case 0:
                        task = this.taskRegistry.get(taskPath);
                        if (!task)
                            throw new Error("Task ".concat(taskPath, " not found"));
                        _a.label = 1;
                    case 1:
                        _a.trys.push([1, 6, , 8]);
                        // 创建任务
                        return [4 /*yield*/, task.create(params)
                            // 启动任务
                        ];
                    case 2:
                        // 创建任务
                        _a.sent();
                        // 启动任务
                        return [4 /*yield*/, task.start(params)
                            // 等待任务完成
                        ];
                    case 3:
                        // 启动任务
                        _a.sent();
                        return [4 /*yield*/, this.waitForCompletion(taskPath)
                            // 处理任务完成
                        ];
                    case 4:
                        result = _a.sent();
                        // 处理任务完成
                        return [4 /*yield*/, task.onFinish(result, params)];
                    case 5:
                        // 处理任务完成
                        _a.sent();
                        return [2 /*return*/, result];
                    case 6:
                        error_1 = _a.sent();
                        // 处理任务失败
                        return [4 /*yield*/, task.onFail(error_1, params)];
                    case 7:
                        // 处理任务失败
                        _a.sent();
                        throw error_1;
                    case 8: return [2 /*return*/];
                }
            });
        });
    };
    // 任务队列执行
    TaskSystem.prototype.executeTaskSequence = function (taskSequence) {
        return __awaiter(this, void 0, void 0, function () {
            var results, _i, taskSequence_1, _a, taskPath, params, result;
            return __generator(this, function (_b) {
                switch (_b.label) {
                    case 0:
                        results = [];
                        _i = 0, taskSequence_1 = taskSequence;
                        _b.label = 1;
                    case 1:
                        if (!(_i < taskSequence_1.length)) return [3 /*break*/, 4];
                        _a = taskSequence_1[_i], taskPath = _a.taskPath, params = _a.params;
                        return [4 /*yield*/, this.executeTask(taskPath, params)];
                    case 2:
                        result = _b.sent();
                        results.push(result);
                        _b.label = 3;
                    case 3:
                        _i++;
                        return [3 /*break*/, 1];
                    case 4: return [2 /*return*/, results];
                }
            });
        });
    };
    // 等待任务完成的Promise
    TaskSystem.prototype.waitForCompletion = function (_taskPath) {
        var _this = this;
        return new Promise(function (resolve, reject) {
            // 设置任务完成的事件监听器
            var onFinished = function (result) {
                resolve(result);
                // 清理监听器
                _this.unsubscribeEvent('sig_task_finished', onFinished);
            };
            var onFailed = function (error) {
                reject(error);
                // 清理监听器
                _this.unsubscribeEvent('sig_task_start_failed', onFailed);
            };
            // 注册事件监听器
            _this.subscribeEvent('sig_task_finished', onFinished);
            _this.subscribeEvent('sig_task_start_failed', onFailed);
            // 模拟任务完成
            setTimeout(function () {
                onFinished({ success: true, message: '任务完成' });
            }, 1000);
        });
    };
    // 事件发布系统
    TaskSystem.prototype.publishEvent = function (_eventName, _data) {
        // 使用现有的事件系统
        console.log("\u53D1\u5E03\u4E8B\u4EF6: ".concat(_eventName), _data);
    };
    TaskSystem.prototype.subscribeEvent = function (_eventName, _handler) {
        // 绑定到现有的事件系统
        console.log("\u8BA2\u9605\u4E8B\u4EF6: ".concat(_eventName));
    };
    TaskSystem.prototype.unsubscribeEvent = function (_eventName, _handler) {
        // 从现有的事件系统解绑
        console.log("\u53D6\u6D88\u8BA2\u9605\u4E8B\u4EF6: ".concat(_eventName));
    };
    return TaskSystem;
}());
exports.TaskSystem = TaskSystem;
// 创建任务系统实例
var taskSystem = new TaskSystem();
exports.taskSystem = taskSystem;
// 定义复苏任务
var tubeRecoveryTask = {
    // 创建任务
    create: function (params) {
        return __awaiter(this, void 0, void 0, function () {
            return __generator(this, function (_a) {
                return [2 /*return*/, createCellTubeAnabiosis(params.taskFlowId, params.parentTaskId)];
            });
        });
    },
    // 开始任务
    start: function (params) {
        return __awaiter(this, void 0, void 0, function () {
            return __generator(this, function (_a) {
                return [2 /*return*/, startCellTubeAnabiosis(params.batchIndex || 0)];
            });
        });
    },
    // 任务完成回调
    onFinish: function (result, params) {
        return __awaiter(this, void 0, void 0, function () {
            return __generator(this, function (_a) {
                // 处理批次完成逻辑
                if (params.hasMoreBatches) {
                    // 自动处理下一批次
                    return [2 /*return*/, taskSystem.executeTask('TubeRecovery/Recovery', __assign(__assign({}, params), { batchIndex: (params.batchIndex || 0) + 1 }))];
                }
                return [2 /*return*/, result];
            });
        });
    },
    // 任务失败回调
    onFail: function (error, _params) {
        return __awaiter(this, void 0, void 0, function () {
            return __generator(this, function (_a) {
                return [2 /*return*/, slotCellTubeAnabiosisFailed(error)];
            });
        });
    }
};
// 注册任务
taskSystem.registerTask('TubeRecovery/Recovery', tubeRecoveryTask);
// 其他任务处理器
var initCellBottleStackTask = {
    create: function (params) {
        return __awaiter(this, void 0, void 0, function () {
            return __generator(this, function (_a) {
                console.log('初始化细胞瓶栈', params);
                return [2 /*return*/, { id: 'init-task-' + Date.now() }];
            });
        });
    },
    start: function () {
        return __awaiter(this, void 0, void 0, function () {
            return __generator(this, function (_a) {
                console.log('开始初始化细胞瓶栈');
                return [2 /*return*/, { success: true }];
            });
        });
    },
    onFinish: function (result, _params) {
        return __awaiter(this, void 0, void 0, function () {
            return __generator(this, function (_a) {
                console.log('细胞瓶栈初始化完成');
                return [2 /*return*/, result];
            });
        });
    },
    onFail: function (error, _params) {
        return __awaiter(this, void 0, void 0, function () {
            return __generator(this, function (_a) {
                console.error('细胞瓶栈初始化失败', error);
                return [2 /*return*/, { success: false, error: error }];
            });
        });
    }
};
var palletInspectionTask = {
    create: function (params) {
        return __awaiter(this, void 0, void 0, function () {
            return __generator(this, function (_a) {
                console.log('创建托盘检查任务', params);
                return [2 /*return*/, { id: 'inspection-task-' + Date.now() }];
            });
        });
    },
    start: function () {
        return __awaiter(this, void 0, void 0, function () {
            return __generator(this, function (_a) {
                console.log('开始托盘检查');
                return [2 /*return*/, { success: true }];
            });
        });
    },
    onFinish: function (result, _params) {
        return __awaiter(this, void 0, void 0, function () {
            return __generator(this, function (_a) {
                console.log('托盘检查完成');
                return [2 /*return*/, result];
            });
        });
    },
    onFail: function (error, _params) {
        return __awaiter(this, void 0, void 0, function () {
            return __generator(this, function (_a) {
                console.error('托盘检查失败', error);
                return [2 /*return*/, { success: false, error: error }];
            });
        });
    }
};
// 注册其他任务
taskSystem.registerTask('TubeRecovery/InitCellBottleStack', initCellBottleStackTask);
taskSystem.registerTask('TubeRecovery/PalletInspectionProcess', palletInspectionTask);
// 任务序列
function runWorkflow() {
    return __awaiter(this, void 0, void 0, function () {
        var taskSequence, results;
        return __generator(this, function (_a) {
            switch (_a.label) {
                case 0:
                    taskSequence = [
                        // {
                        //   taskPath: 'TubeRecovery/InitCellBottleStack',
                        //   params: { tube_panel: 0 }
                        // },
                        // {
                        //   taskPath: 'TubeRecovery/PalletInspectionProcess',
                        //   params: { tube_panel: 0 }
                        // },
                        {
                            taskPath: 'TubeRecovery/Recovery',
                            params: {
                                cellInfo: cellData,
                                batchIndex: 0,
                                hasMoreBatches: true
                            }
                        }
                    ];
                    return [4 /*yield*/, taskSystem.executeTaskSequence(taskSequence)];
                case 1:
                    results = _a.sent();
                    console.log('工作流完成:', results);
                    return [2 /*return*/];
            }
        });
    });
}
runWorkflow();
